var _rowId = "";
var _mash_product_colour_id = 0;

var thisPage = {
    first: 0,
    _rows: 0,
    // 初始化页面
    OnPageLoad: function () {
        thisPage.FetchForPage();
    },
    // 得到数据列表信息
    FetchForPage: function () {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/tech/piece_yardage_onesize/lines/product_colour/fetchByHeaderKey.html",
            timeout: 30 * 1000,
            data: JSON.stringify(parent.$("#HeaderId").val()),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            thisPage.BuildDataTable(data);
        }).fail(function (data) {
            $("#loading").hide();
            ajaxError(data, 1);
            $(".error-msg").css({left: '180px', top: '3px'});
        }).always(function ( ) {
        });
    },
    // 构建数据列表
    BuildDataTable: function (result) {
        if (result === null) {
            $('#loading').hide();
            thisPage._rows = 0;
            return false;
        }
        $("#tabData01 tbody").empty();
        let content_01 = '';
        for (let i = 0; i < result.length; i++) {
            let id = result[i].linesId;
            let sequence = i + 1;
            content_01 += '<tr _mash_id="' + id + '" _mash_old_product_colour_id="' + result[i].productColourId + '">';
            content_01 += '<td style="text-align:center;">' + sequence + '</td>';
            content_01 += '<td class="column__action"><span title="删除" class="trash" onclick="thisPage.DoDelete(\'' + id + '\',' + result[i].productColourId + ');"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            content_01 += '<td>' + result[i].productColourNumber + '</td>';
            content_01 += '<td class="edited-cell" _mash_old_product_colour_id=" ' + result[i].productColourId + '" _mash_product_colour_id="' + result[i].productColourId + '">' + result[i].productColourName + '</td>';
            content_01 += '</tr>';
            $("#tabData01 tbody").append(content_01);
            content_01 = '';
        }
        thisPage._rows = result.length;

        let id = "cell_field";
        let name = "_cell_field";
        $('#tabData01 tbody tr').find("td.edited-cell").click(function () {
            OnCellPopupEditEvent($(this), id, name, thisPage.DoChoiceProductColour);
        });
        setOneTableRowColor("tabData01");
        // 拖动表格行改变显示顺序
        $("#tabData01 tbody").wxdragsort({
            dragWrapper: $("#tabData01"),
            placeHolderWrapper: $("#divD1"),
            parentobj: $("#tabData01"),
            dragColumnIndex: 0,
            dragEnd: function () {
                thisPage.ResetRowNo();
            }
        });
        SetSlaveTableHeight();
        $('#loading').hide();
    },
    $input: null,
    // 编辑成品色
    DoChoiceProductColour: function ($td) {
        parent.showModal(495, 538, '选择成品色', parent.basePath + '/trade/production_instruction/product_colour/choice.html?productId=' + parent.$("#ProductId").val(), null,
                function ($dialog) {
                    var _exist = $.inArray($dialog, parent.arrDialog);
                    if (_exist >= 0) {
                        parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
                    }
                    // 做选择设置
                    if (parent.choice_success) {
                        thisPage.$input.parent().parent().find("td").eq(2).text(parent.arrChoice[0][2]);
                        thisPage.$input.parent().attr("_mash_product_colour_id", parent.arrChoice[0][0]);
                        if (thisPage.$input.parent().attr("_mash_product_colour_id") !== thisPage.$input.parent().attr("_mash_old_product_colour_id")) {
                            thisPage.$input.parent().addClass("dirty");
                        }
                        thisPage.$input.val(parent.arrChoice[0][1]);
                    }
                    // 清空选择结果
                    parent.arrChoice.splice(0, parent.arrChoice.length);
                    parent.choice_success = false;
                    thisPage.$input.focus();
                });
        thisPage.$input = $td;
    },
    // 拖动改变序号
    ResetRowNo: function () {
        // 设置拖动后的每行序号
        $("#tabData01 tbody").find("tr").each(function (index) {
            $(this).find("td").eq(0).text(index + 1);
        });

        let itemResult = [];
        $('#tabData01 tbody').find("tr").each(function (index) {
            let _OrderNo = $.trim($(this).find('td').eq(0).text());   // 顺序号

            let item = {};
            item['headerId'] = parseInt(parent.$("#HeaderId").val());
            item['linesId'] = $.trim($(this).attr("_mash_id"));
            item['orderNo'] = parseInt(_OrderNo);
            item['updatedBy'] = parent.$("#UserId").val();
            itemResult.push(item);
        });

        // 更新后台对应的序号
        $.ajax({
            type: "POST",
            url: parent.basePath + "/tech/piece_yardage_onesize/lines/product_colour/updateLinesOrder.html",
            timeout: 30 * 1000,
            data: JSON.stringify(itemResult),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            if (data.Success === true) {
                thisPage.BuildDataTable(data.ProductColourNode);
                // 得到相关配色方案用成品色
                parent._InstancePageLines.productColourNode = data.ProductColourNode;
                // 显示明细数据
                parent._InstancePageLines.BuildDataTableHeader();
                parent._InstancePageLines.BuildDataTable(data.LinesList);
                ShowSuccessMessagePanel('改变成品色顺序成功。');
                $(".success-msg").css({left: '180px', top: '3px'});
            }
        }).fail(function (data) {
            ajaxError(data, 1);
            $(".error-msg").css({left: '180px', top: '3px'});
        }).always(function ( ) {
        });
    },
    // 增加操作
    DoInsert: function () {
        parent.showModal(1095, 538, '选择颜色', parent.basePath + '/master/colour/choice.html?flag=1', null,
                function ($dialog) {
                    var _exist = $.inArray($dialog, parent.arrDialog);
                    if (_exist >= 0) {
                        parent.arrDialog.splice($.inArray($dialog, parent.arrDialog), 1);
                    }
                    //做列表选择设置
                    if (parent.choice_success) {
                        if (parent.arrChoice[0].length > 0) {
                            let _result = [];
                            for (let i = 0; i < parent.arrChoice[0].length; i++) {
                                let _entity = {};
                                _entity['headerId'] = parseInt(parent.$("#HeaderId").val());
                                _entity['productColourId'] = parseInt(parent.arrChoice[0][i].colourId);

                                _result.push(_entity);
                            }

                            $.ajax({
                                type: "POST",
                                url: parent.basePath + "/tech/piece_yardage_onesize/lines/product_colour/insert.html",
                                timeout: 30 * 1000,
                                data: JSON.stringify(_result),
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                beforeSend: function () {
                                }
                            }).done(function (data) {
                                if (data.Success === true) {
                                    thisPage.BuildDataTable(data.ProductColourNode);
                                    // 得到相关配色方案用成品色
                                    parent._InstancePageLines.productColourNode = data.ProductColourNode;
                                    // 显示明细数据
                                    parent._InstancePageLines.BuildDataTableHeader();
                                    parent._InstancePageLines.BuildDataTable(data.LinesList);
                                    ShowSuccessMessagePanel('成品色增加成功。');
                                    $(".success-msg").css({left: '180px', top: '3px'});
                                }
                            }).fail(function (data) {
                                ajaxError(data, 1);
                                $(".error-msg").css({left: '180px', top: '3px'});
                            }).always(function ( ) {
                            });
                        }

                    }
                    // 清空数组
                    parent.arrChoice.splice(0, parent.arrChoice.length);
                    parent.choice_success = false;
                });
    },
    // 得到明细   
    GetLinesData: function () {
        let jsonResult = [];
        // 得到修改过数据
        $('#tabData01 tbody').find("tr").each(function (index) {
            if ($(this).find("td.dirty").length) {
                let item = {};
                let $row = $(this);

                item['linesId'] = $row.attr("_mash_id");
                item['headerId'] = parseInt(parent.$("#HeaderId").val());
                item['oldProductColourId'] = $row.attr("_mash_old_product_colour_id");
                item['productColourId'] = $row.find("td").eq(3).attr("_mash_product_colour_id");
                item['createdBy'] = parseInt($.trim(parent.$("#UserId").val()));
                item['updatedBy'] = parseInt($.trim(parent.$("#UserId").val()));

                jsonResult.push(item);
            }
        });

        return JSON.stringify(jsonResult);
    },
    // 保存
    SaveLines: function () {
        //step 1、进行页面验证，失败则返回
        //     var success_01 = CheckGridInput();
        //     if (!success_01)
        //         return;

        //step 2、执行处理
        $.ajax({
            type: "POST",
            url: parent.basePath + "/tech/piece_yardage_onesize/lines/product_colour/changeProductColour.html",
            timeout: 30 * 1000,
            data: thisPage.GetLinesData(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            if (data.Success === true) {
                thisPage.BuildDataTable(data.ProductColourNode);
                // 更新单耗表画面
                // 得到相关配色方案用成品色
                parent._InstancePageLines.productColourNode = data.ProductColourNode;
                // 显示明细数据
                parent._InstancePageLines.BuildDataTableHeader();
                parent._InstancePageLines.BuildDataTable(data.LinesList);
                parent.$("#CheckAll").prop("checked", false);
                ShowSuccessMessagePanel('保存成功。');
                $(".success-msg").css({left: '180px', top: '3px'});
            } else {
                ShowErrorMessagePanel('保存失败。');
                $(".error-msg").css({left: '180px', top: '3px'});
            }
        }).fail(function (data) {
            ajaxError(data, 1);
            $(".error-msg").css({left: '180px', top: '3px'});
        }).always(function ( ) {
        });
    },
    // 删除
    DoDelete: function (linesId, productColourId) {
        parent.showModal(350, 140, '确认删除', '', null, null, 1, '请问，确定要删除当前记录吗？',
                function () {
                    var _params = {};
                    _params['headerId'] = parent.$("#HeaderId").val();
                    _params['linesId'] = linesId;
                    _params['productColourId'] = productColourId;

                    $.ajax({
                        type: "POST",
                        url: parent.basePath + "/tech/piece_yardage_onesize/lines/product_colour/delete.html",
                        timeout: 30 * 1000,
                        data: JSON.stringify(_params),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        beforeSend: function () {
                        }
                    }).done(function (data) {
                        if (data.Success === true) {
                            thisPage.BuildDataTable(data.ProductColourNode);
                            // 得到相关配色方案用成品色
                            parent._InstancePageLines.productColourNode = data.ProductColourNode;
                            // 显示明细数据
                            parent._InstancePageLines.BuildDataTableHeader();
                            parent._InstancePageLines.BuildDataTable(data.LinesList);
                            ShowSuccessMessagePanel('成品色删除成功。');
                            $(".success-msg").css({left: '180px', top: '3px'});
                        }
                    }).fail(function (data) {
                        ajaxError(data, 1);
                        $(".error-msg").css({left: '180px', top: '3px'});
                    }).always(function ( ) {
                    });
                });
    }
};

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    thisPage.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    SetSlaveTableHeight();
}

// 根据窗口大小设置明细列表的高度（自适应高度）
function SetSlaveTableHeight() {
    var h = $(window).height();
    var _rc = Math.floor((h - 70) / 25);
    var _dh = _rc * 25;
    var _tah = thisPage._rows * 25;
    _dh = (_tah >= _dh) ? _dh : _tah;

    $("#divD1").css({"max-height": _dh, height: _dh});
}